# (1)	通过OpenCV完成划痕检测并标记
#  题目要求：
# ①　导入相关头文件
import cv2 as cv
import numpy as np
from python_ai.common.xcommon import *

np.random.seed(1)


def rand_color():
    return (
        np.random.randint(0, 256),
        np.random.randint(0, 256),
        np.random.randint(0, 256),
    )


# ②　读取图片
path = '../../../../large_data/CV4/exam/day02/huahen.png'
img = cv.imread(path, cv.IMREAD_GRAYSCALE)
cv.imshow('ori', img)
H, W = img.shape[:2]
print(H, W)

# ③　均值滤波
# ④　均值滤波器核设置合理
# kernel = np.full([3, 3], 1./9.)
# blur = cv.filter2D(img, cv.CV_32F, kernel)
# cv.normalize(blur, blur, 0, 255, cv.NORM_MINMAX)
# blur = np.uint8(blur)
blur = cv.blur(img, (5, 5))
print_numpy_ndarray_info(blur, 'blur')
cv.imshow('blur', blur)

# ⑤　原图和均值图进行作差得到差分图像
diff = cv.subtract(img, blur)
# diff = img - blur
print_numpy_ndarray_info(diff, 'diff')
cv.normalize(diff, diff, 0, 255, cv.NORM_MINMAX)
diff = np.uint8(diff)
print_numpy_ndarray_info(diff, 'diff')
cv.imshow('diff', diff)

# ⑥　完成二值化
ret, bin = cv.threshold(diff, 0, 255, cv.THRESH_OTSU + cv.THRESH_BINARY_INV)
# ret, bin = cv.threshold(gray, 25, 255, cv.THRESH_BINARY_INV)

# ⑦　显示二值图
cv.imshow('bin', bin)

# ⑧　设置保存轮廓的容器
bg = np.zeros([H, W, 3], dtype=np.uint8)

# ⑨　完成轮廓的提取
contours, hierarchy = cv.findContours(bin, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for c in contours:
    cv.drawContours(bg, [c], 0, rand_color())
cv.imshow('contours', bg)

# ⑩　轮廓过滤
result_contours = []
for c in contours:
    rect = cv.minAreaRect(c)

# 11　进行轮廓绘制
# 12　计算轮廓的周长
# 13　在轮廓周围写上12计算出的长度，格式为，“划痕缺陷长度：”

cv.waitKey(0)
cv.destroyAllWindows()
